<template>
  <!-- 现金流 -->
  <zsearch>
      <template #title>
        <span>现金流</span>
      </template>
      <template #date>
        <el-date-picker
          v-model="startTime"
          type="datetime"
          placeholder="选择开始时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          >
        </el-date-picker>

        <el-date-picker
          v-model="endTime"
          type="datetime"
          placeholder="选择结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          >
        </el-date-picker>
      </template>
      <template #select>
        <el-radio-group v-model="selectType">
          <el-radio :label="'明细'">明细</el-radio>
          <el-radio :label="'汇总'">汇总</el-radio>
        </el-radio-group>
      </template>
      <template #btns>
        <el-button class="btn-1" @click="hanledSearch">查询</el-button>
			  <el-button class="btn-2" @click="handleExport">导出</el-button>
      </template>
      <template #table>
        <div class="table-content" v-loading="loading">
          <el-table
          :data="tableData"
          style="width: 100%"
          border
          height='100%'
          :summary-method="hanledAdd"
          show-summary
          
          >
          
            <el-table-column
              v-for="i in columns"
              :prop="i.name"
              :label="i.show">
            </el-table-column>
          </el-table>
        </div>
      </template>
    </zsearch>
</template>

<script lang='ts'>
import { defineComponent, reactive, toRefs, ref, onMounted, watch } from '@vue/runtime-core'

import useRequet, { RespData } from "../../hook/network"
import { cashFlowExportAPi, download } from "../../api/common"

import useConfgin from '../../hook/getconfig'
import { getMonth, getCurrentMonthlastDay } from '../../utils/nowDate'
import { setThousandBit } from '../../usefn/getSeparation'

import ztable from '@components/Table/index.vue'
import zpage from '@components/pagination/pagination.vue'
import zsearch from '@components/search/search.vue'

import { ElMessage } from 'element-plus'

type ColumnType = {
  name: string,
  show: string
}

export default defineComponent({
  name: 'CashFlow',
  components: {
    ztable,
    zpage,
    zsearch
  },
  setup() {
    let search = reactive({
      startTime: `${getMonth()}-01 00:00:00`,
      endTime: `${getCurrentMonthlastDay()} 23:59:59`,
      selectType: '汇总'
    })
    watch(() => search.startTime,(newStartTime) => {
      console.log(newStartTime)
    })
    watch(() => search.selectType, (newType) => {
      console.log(newType)
      req()
    })
    const loading = ref(false)
    const tableData = ref([])
    const columns = ref<ColumnType[]>([])

    const request = useRequet({ path: "" });

    const req = () => {
      loading.value = true
      request.sendRequest({
        address: 'statistical/pay/cashFlow',
        params: search,
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取失败')
          console.log(resp.data)
          if(resp.data) {
            tableData.value = resp.data.data || []
            columns.value = resp.data.title || []
          }
          loading.value = false
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取失败')
          console.log(resp, '错误')
        },
        method: "POST",
      })
      // loading.value = false
    }
    onMounted(() => {
      req()
    })
    //搜索
    const hanledSearch = () => {
      req()
    }

    // 处理小数相加问题
    const speed = 10000000000;
    const hanledAdd = (param:any) => {
      const { columns, data } = param
      const sums = <string[]>[]
      columns.forEach((column:any, index:number) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const values = data.map((item: any) => Number(item[column.property]))
        if (!values.every((value: any) => isNaN(value))) {
          sums[index] = `￥${values.reduce((prev:number, curr: number) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return ((prev * speed) + (curr * speed )) / speed
            } else {
              return Number(prev).toFixed(2)
            }
          }, 0)}`
        } else {
          sums[index] = 'N/A'
        }
      })
      
      return sums
    }

    const handleExport = async() => {
      
      loading.value = true;
      let res:any = await cashFlowExportAPi('statistical/pay/cashFlowExport',search)
      ElMessage.warning('正在导出中，请耐心等待')
      download(res.data, '现金流报表.xlsx')
      ElMessage.warning('导出成功')
      loading.value = false;
    }

    return {
      loading,
      tableData,
      columns,
      ...toRefs(search),
      hanledSearch,
      hanledAdd,
      handleExport,
    }
  }
})
</script>

<style scoped lang="scss">
.table-content {
  height: 100%;
}

</style>